<template>
  <van-icon
    color="#777"
    :name="value === 1 ? 'good-job' : 'good-job-o'"
    :class="value === 1 ? 'success' : ''"
    @click="onLike"
  />
</template>

<script>
import { addLike, deleteLike } from '@/api/article.js'
import { mapState } from 'vuex'

export default {
  name: 'ArticleLike',
  data() {
    return {}
  },
  methods: {
    async onLike() {
      // 防止用户不断的点击发起请求
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '操作中...',
        forbidClick: true // 是否禁止背景点击
      })

      if (this.user) {
        // 判断是否登录
        try {
          /**
           * -1--无态度
           *  0--不喜欢
           *  1--点赞
           * */
          let status = -1 // 状态码
          if (this.value === -1) {
            // 未点赞,发起点赞请求
            await addLike(this.articleId)
            status = 1
            this.$toast.success('点赞成功')
          } else {
            // 点赞了,发起取消点赞请求
            await deleteLike(this.articleId)
            this.$toast.success('取消点赞')
          }
          this.$emit('input', status)
        } catch (error) {
          console.log(error)
          this.$toast.fail('操作失败,请重试')
        }
      } else {
        // 未登录,提示并且跳转登录页
        this.$toast.fail('请先登录')
        this.$router.push('/login')
      }
    }
  },
  props: {
    value: {
      type: Number,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  computed: {
    ...mapState(['user'])
  }
}
</script>

<style scoped lang="less">
/* 文章点赞后颜色 */
.success {
  color: rgb(250, 159, 24) !important;
}
</style>
